package com.faxsun.payment.service.gateway;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.broadleafcommerce.common.money.Money;
import org.broadleafcommerce.common.payment.PaymentTransactionType;
import org.broadleafcommerce.common.payment.PaymentType;
import org.broadleafcommerce.common.payment.dto.PaymentResponseDTO;
import org.broadleafcommerce.common.payment.service.PaymentGatewayWebResponsePrintService;
import org.broadleafcommerce.common.payment.service.PaymentGatewayWebResponseService;
import org.broadleafcommerce.common.vendor.service.exception.PaymentException;
import org.springframework.stereotype.Service;

import com.faxsun.payment.vendor.paysss.service.PaySSSPaymentGatewayType;

@Service("fsPaySSSHostedWebResponseService")
public class PaySSSHostedWebResponseSerivce implements PaymentGatewayWebResponseService {

	@Resource(name = "blPaymentGatewayWebResponsePrintService")
	protected PaymentGatewayWebResponsePrintService webResponsePrintService;

	@Override
	public PaymentResponseDTO translateWebResponse(HttpServletRequest request) throws PaymentException {
		PaymentResponseDTO responseDTO = new PaymentResponseDTO(PaymentType.THIRD_PARTY_ACCOUNT,
				PaySSSPaymentGatewayType.PAYSSS_HOSTED_GATEWAY).rawResponse(webResponsePrintService.printRequest(request));

		@SuppressWarnings("unchecked")
		Map<String, String[]> paramMap = request.getParameterMap();

		Money amount = Money.ZERO;
		if (paramMap.containsKey(PaymentGatewayConstants.ORDER_AMOUNT)) {
			String amt = paramMap.get(PaymentGatewayConstants.ORDER_AMOUNT)[0];
			amount = new Money(amt).divide(100.0);
		}

		String order_id = paramMap.get(PaymentGatewayConstants.ORDER_ID)[0].split(PaymentGatewayConstants.ORDER_ID_DELIMITER)[0];

		responseDTO.successful(true)
				// .completeCheckoutOnCallback(Boolean.parseBoolean(paramMap.get(PaymentGatewayConstants.COMPLETE_CHECKOUT_ON_CALLBACK)[0]))
				.amount(amount)
				.paymentTransactionType(PaymentTransactionType.AUTHORIZE_AND_CAPTURE)
				.orderId(order_id)
				// .responseMap(PaymentGatewayConstants.RESULT_MESSAGE,
				// "通过小灵通支付成功");
				.responseMap(PaymentGatewayConstants.RESULT_MESSAGE,
						(String) request.getAttribute(PaymentGatewayConstants.RESULT_MESSAGE));

		return responseDTO;
	}
}
